import $Request from '@/api'
import store from '@/store'
import { setCompanyId, removeCompanyId, setItem } from '@/utils/auth'

let loadUserInfo = () => {
  removeCompanyId()
  return new Promise((resolve, reject) => {
    $Request.commonApi.fetchUserInfo().then(resp => {
      if (resp.code === 0) {
        let { data } = resp
        let companyId = data.companyList[0].id
        store.commit('user/SET_USERINFO', data)
        setCompanyId(companyId)
        resolve(data)
      }
    })
  })
}

async function loadMenuRequest() {
  return new Promise((resolve, reject) => {
    $Request.commonApi.fetchMenuRoutes().then(resp => {
      if (resp.code === 0) {
        let { menuDataList } = resp.data
        resolve(resp.data.menuDataList)
        setItem('menuRouters', JSON.stringify(menuDataList))
        store.commit('menu/SET_ROUTERS', menuDataList)
      }
    })
  })
}

export default async function loadMenuFn() {
  await loadUserInfo()
  return loadMenuRequest()
}
